package com.platform.common.task;

import cn.hutool.extra.spring.SpringUtil;
import com.platform.modules.sys.domain.SysTask;
import com.platform.modules.sys.service.SysTaskService;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTask;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.lang.reflect.Method;
import java.util.List;

@Component
@EnableScheduling
public class ScheduleTask implements SchedulingConfigurer {

    private static ScheduledTaskRegistrar taskRegistrar;

    @Resource
    private SysTaskService sysTaskService;

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        this.taskRegistrar = taskRegistrar;
        // 执行task
        this.doTask();
    }

    /**
     * 执行task
     */
    private void doTask() {
        // 1、查询激活状态下的task
        List<SysTask> sysTaskList = sysTaskService.queryActivateList();
        if (CollectionUtils.isEmpty(sysTaskList)) {
            return;
        }
        for (SysTask sysTask : sysTaskList) {
            taskRegistrar.addTriggerTask(() -> {
                invoke(sysTask.getMethods());
            }, triggerContext -> {
                String cron = sysTask.getCron();
                return new CronTrigger(cron).nextExecutionTime(triggerContext);
            });
        }
    }

    private void invoke(String url) {
        try {
            int length = url.lastIndexOf(".");
            // 获取class对象
            Class<?> cls = Class.forName(url.substring(0, length));
            // 获取mybatis方法
            Method method = cls.getMethod(url.substring(length + 1));
            // 执行方法
            method.invoke(SpringUtil.getBean(cls));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 重置
     */
    public void reload() {
        // 1、清空任务
        for (ScheduledTask task : taskRegistrar.getScheduledTasks()) {
            task.cancel();
        }
        // 2、任务列表置空
        taskRegistrar.setTriggerTasksList(null);
        // 3、执行task
        this.doTask();
        // 4、重置
        taskRegistrar.afterPropertiesSet();
    }

    /**
     * 运行一次
     */
    public void run(Long id) {
        SysTask sysTask = sysTaskService.getById(id);
        if (sysTask != null) {
            invoke(sysTask.getMethods());
        }
    }
}
